package com.azdebugit.future.vip.executorcompletion.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
 
/**
 * 描    述：多线程处理容器（菜鸟直接用即可,尽量不要改动这里）
 * 作    者：java潇邦
 * 时    间：2016-09-01
 */
@Component
public class BatchContainerExecutor {
 
    private static final Logger logger = LoggerFactory.getLogger(BatchContainerExecutor.class);
 
    private static ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
 
    /**
     * 功    能：并发处理taskList中的任务
     * 作    者：java潇邦
     * 时    间：2016-09-01
     */
    public List<Object> execute(List<Callable<Object>> taskList) {
        int taskSize = taskList.size();
        List<Object> results = new ArrayList<Object>(taskSize);
        ExecutorCompletionService<Object> concurrentExecutor = new ExecutorCompletionService<Object>(pool);
        for (Callable<Object> callable : taskList) {
            concurrentExecutor.submit(callable);
        }
        for (int i = 0; i < taskSize; i++) {
            Object result = getQuenueMsg(concurrentExecutor);
            results.add(result);
        }
        return results;
    }
 
    /**
     * 功    能：并发处理taskList中的任务***如果有任务发生异常,则取消剩余任务
     * 作    者：java潇邦
     * 时    间：2016-09-01
     */
    public List<Object> execute(List<Callable<Object>> taskList, ExecutorService pool) {
        int taskSize = taskList.size();
        List<Object> results = new ArrayList<Object>(taskSize);
        List<Future<Object>> futures = new ArrayList<Future<Object>>(taskSize);
        ExecutorCompletionService<Object> concurrentExecutor = new ExecutorCompletionService<Object>(pool);
        for (Callable<Object> callable : taskList) {
            futures.add(concurrentExecutor.submit(callable));
        }
        boolean flag = false;
        for (int i = 0; i < taskSize; i++) {
            Object result = null;
            try {
                result = getQuenueMsgThrow(concurrentExecutor);
            } catch (BusinessException e) {
                logger.warn("BatchContainerExecutor获取某个任务异常:", e);
                flag = true;
                break;
            }
            results.add(result);
        }
        if (flag) {
            logger.warn("BatchContainerExecutor出现异常,取消本组taskList剩余任务");
            for (Future<Object> future : futures) {
                try {
                    future.cancel(true);
                } catch (Exception e) {
                    logger.warn("BatchContainerExecutor取消任务异常:", e);
                }
            }
        }
        return results;
    }
 
    /**
     * 功    能：并发处理taskList中的任务***如果取到第一个想要的结果,则取消剩余任务
     * 作    者：java潇邦
     * 时    间：2016-09-01
     */
    public List<Object> executeFirst(List<Callable<Object>> taskList) {
        int taskSize = taskList.size();
        List<Future<Object>> futures = new ArrayList<Future<Object>>(taskSize);
        List<Object> results = new ArrayList<Object>(taskSize);
        try {
            ExecutorCompletionService<Object> concurrentExecutor = new ExecutorCompletionService<Object>(pool);
            for (Callable<Object> callable : taskList) {
                futures.add(concurrentExecutor.submit(callable));
            }
            for (int i = 0; i < taskSize; i++) {
                Object result = getQuenueMsg(concurrentExecutor);
                if (result != null){//假设不为空是第一个想要数据
                    results.add(result);
                    return results;
                }
            }
        } catch (Exception e) {
            logger.warn("executeFirst:", e);
        } finally {
            for (Future<Object> future : futures) {
                try {
                    future.cancel(true);
                } catch (Exception e) {
                    logger.warn("取消任务:", e);
                }
            }
        }
        return results;
    }
 
    /**
     * 功    能：获取任务-超时时间为10秒
     * 作    者：java潇邦
     * 时    间：2016-09-01
     */
    private Object getQuenueMsg(ExecutorCompletionService<Object> concurrentExecutor) {
        Object result = null;
        try {
            result = concurrentExecutor.poll(10, TimeUnit.SECONDS).get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.warn("获取线程执行结果异常:", e);
            result = e.getMessage();
        }
        return result;
    }
 
    /**
     * 功    能：获取任务-超时时间为10秒
     * 作    者：java潇邦
     * 时    间：2016-09-01
     */
    private Object getQuenueMsgThrow(ExecutorCompletionService<Object> concurrentExecutor) {
        Object result = null;
        try {
            result = concurrentExecutor.poll(10, TimeUnit.SECONDS).get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.warn("获取线程执行结果异常:", e);
            throw new BusinessException("获取线程执行结果异常");
        }
        return result;
    }
 
    static class BusinessException extends RuntimeException {
        public BusinessException(Throwable cause) {
            super(cause);
        }
 
        public BusinessException(String message) {
            super(message);
        }
 
        public BusinessException(String message, Throwable cause) {
            super(message + cause.getMessage());
        }
    }
}